package com.hgd.igreencar.nettytest;

import com.hgd.igreencar.entity.RpcRequest;
import com.hgd.igreencar.entity.RpcResponse;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import javax.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
@Component
public class NettyServer {
    @Resource
    private ServerHandler serverHandler;

    @PostConstruct
    public void bind() throws Exception {
        int port = 8080;
        EventLoopGroup bossgroup = new NioEventLoopGroup();
        EventLoopGroup workergroup = new NioEventLoopGroup();

        ServerBootstrap sb = new ServerBootstrap();
        sb.group(bossgroup, workergroup)
                .channel(NioServerSocketChannel.class)
                .option(ChannelOption.SO_BACKLOG, 128)
                .childOption(ChannelOption.SO_KEEPALIVE, true)
                .childHandler(new ChannelInitializer<SocketChannel>() {

                    protected void initChannel(SocketChannel ch) throws Exception {
                        ch.pipeline()
                                .addLast(new RpcDecoder(RpcRequest.class)) //解码request
                                .addLast(new RpcEncoder(RpcResponse.class)) //编码request
                                .addLast(new ServerHandler()); //使用SeverHandler类来处理接收到的消息
                    }
                });
        //绑定监听端口，调用sync同步阻塞方法等待绑定操作完
        ChannelFuture future = sb.bind(port).sync();

        if (future.isSuccess()) {
            System.out.println("服务器启动成功");
        } else {
            System.out.println("服务器启动失败");
            future.cause().printStackTrace();
            bossgroup.shutdownGracefully();
            workergroup.shutdownGracefully();
        }

        //成功绑定到端口后，给channel增加一个管道关闭的监听器并同步阻塞，直到channel关闭，线程才会往下执行，结束进程
        future.channel().closeFuture().sync();
    }
}
